﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;

/// <summary>
///ExcelManager 的摘要说明
/// </summary>
public class ExcelManager
{
    public ExcelManager()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    public static void Output(ConfigTable cTab,string listType,string listValue)
    {        
        //获取数据
        string sql = cTab.GetListBaseSql() + cTab.GetListWhereSql(listType, listValue) + cTab.GetListOrderSql();
        DataTable tab = DBFactory.GetConn().exeTable(sql);
        GridView gv = new GridView();
        gv.AutoGenerateColumns = false;
        foreach (ConfigColumns cCol in cTab.Columns.Where(x => x.IsListShow && (x.ListShowType == Etong.Web.ListShowType.Text || x.ListShowType== Etong.Web.ListShowType.TextEncode|| x.ListShowType== Etong.Web.ListShowType.BoolLink)).OrderBy(x => x.ListShowOrder))
        {

            gv.Columns.Add(ListShowFactory.GetListColumnTypeClass(Etong.Web.ListShowType.BoundLink).GetListField(cCol));
        }
        gv.DataSource = tab;
        gv.DataBind();
        HttpResponse Response = HttpContext.Current.Response;

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "utf-8";
        Response.AppendHeader("Content-Disposition", "attachment;filename="+cTab.TableName+"Output.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        //设置输出流为简体中文 
        Response.ContentType = "application/ms-excel";
        //设置输出文件类型为excel文件。 
        (HttpContext.Current.CurrentHandler as Page).EnableViewState = false;
        //System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true); 
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
        gv.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }
}
